package com.gpj.learn.rabbitmq.workqueue;

import com.gpj.learn.rabbitmq.common.CommonConstants;
import com.gpj.learn.rabbitmq.common.RabbitUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @className WorkQueueConsumer1
 * @description
 *   TODO
 * @author GPJ
 * @date 2021/5/30 12:33
 * @version 1.0
 **/
@Slf4j
public class WorkQueueConsumer2 {
	public static void main(String[] args) throws IOException {
		log.info("------------- 开始消费消息 -------------");
		Channel channel = RabbitUtil.createChannel(CommonConstants.RABBITMQ_QUEUE_WORKQUEUE);

		channel.basicQos(1); // 见WorkQueueConsumer1

		RabbitUtil.consumeMessage(channel, CommonConstants.RABBITMQ_QUEUE_WORKQUEUE, new DefaultConsumer(channel){
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				String message = new String(body);
				log.info("[{}]接收到消息[{}]:{}", "WorkQueueConsumer2", envelope.getDeliveryTag(), message);
				//false只确认签收当前的消息，设置为true的时候则代表签收该消费者所有未签收的消息
				channel.basicAck(envelope.getDeliveryTag(), false);
			}
		});
	}
}
